package com.jboost.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
@Aspect
@Slf4j
@ConditionalOnProperty(prefix = "controller.log",name = "enabled",havingValue = "true")
public class ControllerAop {

    static {
        System.out.println(1);
    }

    @Pointcut("execution(public * com..*Client.*(..))" +
            "||execution(public * com..*Client.*(..))")
    public void logPointCutMethod(){
    }
    @Around("logPointCutMethod()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        Object ob;
        String username = "";
        long startTime = System.currentTimeMillis();
        String requestIp = getRequestIp();
        try {
            log.info("[控制器访问监控]用户：{} 请求ip: {} 请求方法开始：{}.{} 执行开始时间：{}ms 请求参数：{}", username, requestIp,
                    pjp.getTarget().getClass().getName(), pjp.getSignature().getName(),
                    startTime, args);
            ob = pjp.proceed();
            log.info("[控制器访问监控]用户：{} 请求ip: {} 请求方法结束：{}.{} 执行时长：{}ms 请求参数：{} 成功返回：{}", username, requestIp,
                    pjp.getTarget().getClass().getName(), pjp.getSignature().getName(),
                    (System.currentTimeMillis() - startTime), args, ob);
        } catch (Throwable t) {
            ob = t.getMessage();
            log.error("[控制器访问监控]用户：{} 请求ip: {} 请求方法结束：{}.{} 执行时长：{}ms 请求参数：{} 错误返回：{}", username, requestIp,
                    pjp.getTarget().getClass().getName(), pjp.getSignature().getName(),
                    (System.currentTimeMillis() - startTime), args, ob);
            throw t;
        }
        return ob;
    }

    public String getRequestIp() {
        try {
            HttpServletRequest httpServletRequest =
                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return getIp(httpServletRequest);
        } catch (Exception exception) {
            return "";
        }
    }

    private String getIp(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return "";
        }
        return request.getRemoteHost();
    }
}
